import React, { useContext } from "react";
import classnames from "classnames";
import { ThemeContext } from "../theme";
import type { RadioProps, RadioOption } from "./type";

export default function Radio<T>({
  value,
  options = [],
  border,
  disabled,
  style,
  className,
  onChange,
}: RadioProps<T>) {
  const clickHandler = (option: RadioOption<T>) => {
    if (disabled || option.disabled) return;
    if (option.value === value) return;
    onChange?.(option.value);
  };

  const { fontSize } = useContext(ThemeContext);

  return (
    <div
      className={classnames("ct0-radio-container", className)}
      style={{
        fontSize,
        ...style,
      }}
      data-testid="radio"
    >
      {options.map((x, index) => (
        <div
          key={index}
          className={classnames(
            "ct0-radio-option",
            border && "border",
            value === x.value && "active",
            (disabled || x.disabled) && "ct0-radio-option-disabled"
          )}
          onClick={() => clickHandler(x)}
          role="option"
          aria-selected={value === x.value}
        >
          <b className="spot" />
          <span>{x.label}</span>
        </div>
      ))}
    </div>
  );
}
